import {Component,ViewChild } from '@angular/core';
import {NavController, NavParams,Content,Navbar} from 'ionic-angular';
import {Storage} from '@ionic/storage';
import {dialogUtil} from "../../../service/dialogUtil";
import {SQLite, SQLiteObject} from '@ionic-native/sqlite';
import * as io from 'socket.io-client';
import {httpService} from "../../../service/httpService";
import {HOST_URL} from "../../../service/Constants";

/**
 *
 */
let socket = io('http://192.168.31.144:3001');
@Component({
  selector: 'page-chat-view',
  templateUrl: 'chat-view.html',
})
export class ChatView {
  @ViewChild(Content) content: Content;
  @ViewChild(Content) navBar: Navbar;
  contentText;
  user;
  targetUser;
  token;
  chatLog;
  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              public storage: Storage,
              private dialog: dialogUtil,
              private sqlite: SQLite,
              private http: httpService,) {
    //目标联系人信息
    this.targetUser = navParams.get('item');
    this.storage.get("token").then(data => {
      this.token = data;
    });
    //用户信息
    this.storage.get("userInfo").then(data => {
      this.user = data;
      //监听目标人发送的信息
      this.loadLog();
      socket.on(this.targetUser.userCode + 'to' + this.user.userCode,  (data)=> {
        this.loadLog();
      });
    });
  }

  database: SQLiteObject;
  //获取聊天记录
  loadLog() {
    let date=new Date();
    //当前日期
    let today=date.getFullYear()+"-"+((date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : '0' + (date.getMonth() + 1))+'-'
      + (date.getDate() > 9 ? date.getDate() : '0'+"-"+date.getDate());
    this.http.get(HOST_URL + '/api/v1/chat_log/?filter=', {
      or: [{idUser: this.user.id,idTargetUser: this.targetUser.id}, {idUser: this.targetUser.id,idTargetUser: this.user.id}],
      logState: '1'
    }, this.token).then(res => {
      if (res.error.code == '0') {
        this.chatLog=res.rows;
        this.chatLog.forEach(function (item) {//时间格式转换
            let dateObj = new Date(item.updatedAt);
            //消息发送年-月-日
            let msgDate=dateObj.getFullYear() + '-' +( (dateObj.getMonth() + 1) > 9 ? (dateObj.getMonth() + 1) : '0' + (dateObj.getMonth() + 1))+'-'
              + (dateObj.getDate() > 9 ? dateObj.getDate() : '0' + dateObj.getDate() );
          //消息发送时:分:秒
            let time=( dateObj.getHours() > 9 ? dateObj.getHours() : '0' + dateObj.getHours() )+ ':'
              + (dateObj.getMinutes() > 9 ? dateObj.getMinutes() : '0' + dateObj.getMinutes()) + ':'
              + (dateObj.getSeconds() > 9 ? dateObj.getSeconds() : '0' + dateObj.getSeconds());
          //如果消息发送时间是当天，只显示时分秒
            if(today==msgDate){
              item.updatedAt= time
            }else{
              item.updatedAt=msgDate + ' '+time
            }

        });
        //滚动到底部
        this.content.scrollTo(0,5000000,200).then(()=>{});

      } else if (res.error.code == '801') {

      }
    })
  }

  toSendMsg() {
    if (this.contentText) {
      socket.emit('private message', this.user.userCode, this.targetUser.userCode, this.contentText);
      this.http.postBody(HOST_URL + '/api/v1/chat_log', {
        idUser: this.user.id,
        idTargetUser: this.targetUser.id,
        logType: 'text',
        logContent: this.contentText,
        logState: '1'
      }, this.token).then(res => {

        if (res.error.code == '0') {
          this.loadLog();
          this.contentText='';
        } else if (res.error.code == '801') {

        }
      })
      //sqlite
      /* this.sqlite.create({
       name: 'data.db',
       location: 'default'
       }).then((db: SQLiteObject) => {
       db.executeSql('create table t_log(name VARCHAR(32))', {})
       .then(() => console.log('Executed SQL'))
       .catch(e => alert(JSON.stringify(e)));
       this.database = db;
       db.executeSql("insert into t_log values("+this.contentText+")", {}).then(() => alert('chengong')).catch(e => alert(JSON.stringify(e)));
       })
       .catch(e => console.log(e));*/
    } else {
      this.dialog.showAlert('消息不能为空')
    }
  }

  //查询
  /* goChatView() {
   this.database.executeSql("select * from t_log", [])
   .then((data) => {
   debugger;
   alert( data.rows.item(0).name)
   })
   .catch(e => alert('shibai'+JSON.stringify(e)));
   }
   ionViewDidLoad() {

   }*/

  /* toSendMsg(){
   if(this.contentText){
   // this.socket.sendMessage(this.contentText)
   this.sqlite.create({
   name: 'data.db',
   location: 'default'
   })
   .then((db: SQLiteObject) => {
   db.executeSql('CREATE TABLE IF NOT EXISTS t_chatLog(name VARCHAR(32))', {})//建表
   .then(() => console.log('Executed SQL'))
   .catch(e => alert(JSON.stringify(e)));

   this.database = db;
   //插入数据
   db.executeSql("INSERT INTO t_chatLog VALUES('123')", {}).then(()=>alert('chengong')).catch(e => alert(JSON.stringify(e)));
   })
   .catch(e => console.log(e));


   }else{
   this.dialog.showAlert('消息不能为空')
   }
   }
   */

}
